from qcloud_cos import CosConfig, CosS3Client
import os
import logging

# 腾讯云SecretId
TENCENT_SECRET_ID=os.getenv('TENCENT_SECRET_ID')
# 腾讯云SecretKey
TENCENT_SECRET_KEY=os.getenv('TENCENT_SECRET_KEY')
# 腾讯云存储区域
TENCENT_REGION=os.getenv('TENCENT_REGION')
# 腾讯云存储桶名称
TENCENT_BUCKET=os.getenv('TENCENT_BUCKET')
# 令牌，默认为None
TENCENT_TOKEN = None
# 访问协议，默认为https
TENCENT_SCHEME = "https"

logger = logging.getLogger(__name__)


def upload_to_cos(stream, key):
    # 创建CosConfig对象，配置COS客户端参数
    config = CosConfig(
        Region=TENCENT_REGION,
        SecretId=TENCENT_SECRET_ID,
        SecretKey=TENCENT_SECRET_KEY,
        Token=TENCENT_TOKEN,
        Scheme=TENCENT_SCHEME
    )

    # 创建CosS3Client客户端对象
    client = CosS3Client(config)
    # 调用put_object方法上传对象到COS
    client.put_object(
        Bucket=TENCENT_BUCKET,
        Body=stream,
        Key=key,
        StorageClass="STANDARD",
        EnableMD5=False
    )
    # 构造文件的访问URL
    url = f"{TENCENT_SCHEME}://{TENCENT_BUCKET}.cos.{TENCENT_REGION}.myqcloud.com/{key}"
    logger.info(f"文件已上传，访问地址：{url}")
    return url
